<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8>
<title></title>
<script>
var canvas, ctx, image, fadeTimer, alphaBar;
function init() {
  canvas = document.getElementById("canvas");
  ctx = canvas.getContext("2d");
  image = new Image();
  image.onload = function() {
    showImage();
  };
  image.src = "image.png";
  alphaBar = document.getElementById("alphaBar");
}
function showImage() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.drawImage(image, 0, 0);
}
function fadeIn() {
  stopAnimation();
  fadeTimer = setInterval(function() {
    if (ctx.globalAlpha > 0.9) {
      ctx.globalAlpha = 1;
      stopAnimation();
    } else {
      ctx.globalAlpha += 0.1;
    }
    showImage();
    alphaBar.value = ctx.globalAlpha;
  }, 200);
}
function fadeOut() {
  stopAnimation();
  fadeTimer = setInterval(function() {
    if (ctx.globalAlpha < 0.1) {
      ctx.globalAlpha = 0;
      stopAnimation();
    } else {
      ctx.globalAlpha -= 0.1;
    }
    showImage();
    alphaBar.value = ctx.globalAlpha;
  }, 200);
}
function stopAnimation() {
  if (fadeTimer) {
    clearInterval(fadeTimer);
    fadeTimer = null;
  }
}
function changeAlpha() {
  stopAnimation();
  ctx.globalAlpha = alphaBar.value;
  showImage();
}
</script>
</head>
<body onload="init()">
<canvas id="canvas" width=300 height=300></canvas><br>
<button onclick="fadeIn()">フェードイン</button>
<input id=alphaBar type=range step=0.1 value=1 max=1 min=0 onchange="changeAlpha()">
<button onclick="fadeOut()">フェードアウト</button>
</body>
</html>
